package com.usian.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.constant.WemediaConstants;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmNewsDto;
import com.usian.model.media.dtos.WmNewsPageReqDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmNewsService;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Resource
    private WmMaterialMapper wmMaterialMapper;
    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult findPage(WmNewsPageReqDto dto) {
        //判断参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查分页参数
        dto.checkParam();
      /*  //判断用户登录的状态
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE);
        }*/
        //判断查询的条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        //状态
        queryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //关键字
        queryWrapper.like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());
        //频道
        queryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //时间
        queryWrapper.between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        //开始分页
        Page pageInfo = new Page(dto.getPage(), dto.getSize());
        IPage page = page(pageInfo, queryWrapper);
        //结果封装
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult submit(WmNewsDto dto,Integer status) {
        //1.判断wmNewsDto是否为null
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存新闻
        //2.1获取用户id
        Integer uid = WmThreadLocalUtils.getUser().getApUserId();
        if (uid == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_EXPIRE);
        }
         //保存新闻
        WmNews wmNews = saveContent(dto, uid,status);
        //获取图片中的url
        List<String> imageUrl = getContentImageUrl(dto);
        //保存内容图片和素材之间的关系
        saveContentImageMaterial(imageUrl, wmNews, WemediaConstants.WM_CONTENT_REFERENCE);
        saveInFoImage(imageUrl, wmNews, dto);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @Override
    public ResponseResult findByIdNews(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews w = getById(id);
        ResponseResult result = ResponseResult.okResult(w);
        return result;
    }

    @Override
    public ResponseResult updateStatusAndReason(WmNews wmNews) {
        LambdaUpdateWrapper<WmNews> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmNews::getStatus,wmNews.getStatus());
        updateWrapper.set(WmNews::getReason,wmNews.getReason());
        updateWrapper.eq(WmNews::getId,wmNews.getId());
        update(updateWrapper);
        return ResponseResult.okResult("ok");
    }

    //保存封面图片与文件之间的关联
    public ResponseResult saveInFoImage(List<String> imageUrl,WmNews wmNews,WmNewsDto dto){
        //保存封面与新闻的关联
        if(dto.getType()==WemediaConstants.WM_NEWS_TYPE_AUTO){
            //获取内容中的图片数量
            int picNum = imageUrl.size();
            if(picNum>0){
                //3张图
                wmNews.setType(WemediaConstants.WM_NEWS_CONENT_MANY_IMAGE);
                //取三张图
                imageUrl = imageUrl.stream().limit(3).collect(Collectors.toList());
            }else if(picNum<=2 &&picNum>0){
                //1张图
                wmNews.setType(WemediaConstants.WM_NEWS_CONENT_SINGLE_IMAGE);
                imageUrl = imageUrl.stream().limit(1).collect(Collectors.toList());
            }else {
                //说明无图
                wmNews.setType(WemediaConstants.WM_NEWS_CONENT_NONE_IMAGE);
            }
        }
        //修改wm_news_material表中的images字段喝wmNews字段
        LambdaUpdateWrapper<WmNews> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmNews::getType,wmNews.getType());
        updateWrapper.set(WmNews::getImages, imageUrl.toString().replace("{", "").replace("}", "").replace(" ", "").trim());
        updateWrapper.eq(WmNews::getId, wmNews.getId());
        update(updateWrapper);
        //根据封面图片的url找出对应的id
        List<Integer> ids = findByURL(imageUrl, wmNews);
        wmNewsMaterialMapper.insertContentMeterial(ids, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        return null;
    }
    //保存新闻
    public WmNews saveContent(WmNewsDto wmNewsDto,Integer id,Integer status){

        //2.2将WmNewsDto的数据保存到wmNews对象
        WmNews wmNews = add(wmNewsDto);
        if (wmNews.getId()==null){
            //说明是添加
            wmNews.setUserId(id);
            wmNews.setStatus(status);
            //从wmNewsDto获取对应的封面图片保存在wm_news表中
            String imagStr = wmNewsDto.getImages().toString();
            //判断imagStr是否为null
            if(imagStr!=null && imagStr.length()>0){
                //不为null  封面图片不是无图或自动
                String newimgstr = imagStr.replace("[", "").replace("]", "").replace(" ", "");
                wmNews.setImages(newimgstr);
            }
            //保存
            save(wmNews);
        }else {
            //说明是修改 避免重复添加 先进行删除
            LambdaUpdateWrapper<WmNewsMaterial> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(WmNewsMaterial::getId,wmNews.getId());
            wmNewsMaterialMapper.delete(updateWrapper);
            //更新
            updateById(wmNews);
        }

        return wmNews;
    }
    //获取内容中的图片的url
    public List<String> getContentImageUrl(WmNewsDto dto){
        //获取内容图片的URL
        String content = dto.getContent();
        //将新闻内容通过fastjson解析成map形式
        List<Map> maps = JSON.parseArray(content, Map.class);
        //新建一个集合保存通过URL
        ArrayList<String> imageUrl = new ArrayList<>();
        for (Map<String,String> map : maps) {
            if(map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)){
                String url = map.get("value");
                if(url!=null){
                    imageUrl.add(url);
                }
            }
        }
        return imageUrl;
    }
    //根据url获取对应图片的id
    public List<Integer> findByURL(List<String> imageUrl,WmNews wmNews){
        //获取图片的URL去查询图片的id
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        //设置URL条件
        queryWrapper.in(WmMaterial::getUrl,imageUrl);
        //设置用户id
        queryWrapper.eq(WmMaterial::getUserId,wmNews.getUserId());
        //获取对应的图片的数据
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);
        //键值对 id,url
        Map<String, Integer> collect = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        //声明List集合保存图片的id
        List<Integer> ids = new ArrayList<>();
        //遍历imageUrl
        for (String url : imageUrl) {
            Integer id = collect.get(url);
            /*if(id==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"无效图片");
            }*/
            ids.add(id);
        }
        return ids;
    }
     //保存内容图片和素材之间的关系
    public ResponseResult saveContentImageMaterial(List<String> imageUrl,WmNews wmNews,Integer type){
        List<Integer> ids = findByURL(imageUrl, wmNews);
        //获取新闻的id
        Integer newsId = wmNews.getId();
        //执行保存
        wmNewsMaterialMapper.insertContentMeterial(ids, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
        return null;
    }
    //将WmNewsDto的数据保存到wmNews对象
    public WmNews add(WmNewsDto wmNewsDto) {
        WmNews wmNews = new WmNews();
        wmNews.setChannelId(wmNewsDto.getChannelId());
        wmNews.setContent(wmNewsDto.getContent());
        wmNews.setCreatedTime(new Date());
        wmNews.setLabels(wmNewsDto.getLabels());
        wmNews.setTitle(wmNewsDto.getTitle());
        wmNews.setType(wmNewsDto.getStatus());
        wmNews.setSubmitedTime(new Date());

        return wmNews;
    }
}
